<template>
  <div class="box">
    <div class="content" v-for="item in goodslist" :key="item.id">
      <router-link :to="'/goodsinfo/'+item.id">
        <div class="image-con">
          <img :src="item.image" alt="">
        </div>
        <div class="name">{{item.name}}</div>
        <div class="text">
          <span class="price">￥{{item.price}}</span>
          <span class="number">剩余{{item.num}}件</span>
        </div>
      </router-link>
    </div>
    <mt-button class="btn" @click="getMore">加载更多</mt-button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      category_id: -1,
      last_id: 0,
      goodslist: []
    }
  },
  created() {
    this.getGoodsList()
  },
  methods: {
    // 根据分类里传来的id，来查询对应的商品列表信息
    getGoodsList() {
      // 获取category_id      
      this.category_id = this.$route.params.id;
      var params = {
        category_id: this.category_id,
        last_id: this.last_id
      }
      this.$http.get('goodslist', {params}).then(res => {
        // console.log(res.data);
        if (res.data.code === 1) {
          // 为了之后的加载更多，要把后来添加的信息添加在goodslist后面
          res.data.data.forEach(item => {
            this.goodslist.push(item)
          })
          
          console.log(this.goodslist);
        } else {
          this.$toast('商品列表获取失败')
        }
      })
    },
    // 加载更多
    getMore() {
      if (this.goodslist.length > 0) {
        var id = this.goodslist[this.goodslist.length - 1].id
        if (id !== this.last_id) {
          this.last_id = id
          this.getGoodsList();
        } else {
          this.$toast('已经到底了')
        }
      }
    }
  }

}
</script>

<style lang="scss" scoped>
.box {
  .content {
    display: inline-block;
    width: calc(50% - 10px);
    text-align: center;
    padding: 10px 5px;
    margin: 5px;
    font-size: 14px;
    background-color: #fff;
    border-radius: 10px;
    font-weight: 700;
    .image-con {
      
      img {
        width: 90%;
      }
    }
    .name {
      padding-top: 5px;
      text-align: left;
      color: #000;
    }
    .text {
      
      .price {
        float: left;
        color: crimson;
        padding-top: 5px;
      }
      .number {
        float: right;
        color: #999;
        font-weight: 500;
      }
    }
  }
  .btn {
    width: 90%;
    
    margin: 10px 5%;
  }
}
</style>